package com.czl.module_service.fragment.sort

import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.util.GlideEngine
import com.czl.base.util.SpHelper
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.AddSortAdapter
import com.czl.module_service.databinding.FooterAddSortBinding
import com.czl.module_service.databinding.FragmentAddSortBinding
import com.czl.module_service.event.SortBeanEvent
import com.czl.module_service.system.Constants
import com.czl.module_service.view.DividerItemDecoration
import com.czl.module_service.view.ListSheetDialogFragment
import com.czl.module_service.viewmodel.AddSortViewModel
import com.github.nikartm.button.util.dpToPx
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import java.util.*

/**
 * @author by xubin,
 * @date on 2022/1/20.
 * PS: Not easy to write code, please indicate.
 */
@Route(path = AppConstants.Router.Service.F_SERVICE_SORT_ADD)
class AddSortFragment : BaseFragment<FragmentAddSortBinding, AddSortViewModel>() {

    private var footerBinding: FooterAddSortBinding? = null

    private val selectList: ArrayList<LocalMedia> = ArrayList()

    private val mAdapter: AddSortAdapter by lazy {
        AddSortAdapter(viewModel.data).apply {
            val view = FooterAddSortBinding.inflate(layoutInflater)
            footerBinding = DataBindingUtil.bind(view.root)
            footerBinding?.setVariable(initVariableId(), viewModel)
            addFooterView(footerBinding?.root!!)
            setOnItemClickListener { _, _, position ->
                itemCommand(position)
            }
        }
    }

    override fun initContentView(): Int {
        return R.layout.fragment_add_sort
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        super.initData()
        binding.recyclerView.run {
            adapter = mAdapter
            addItemDecoration(
                DividerItemDecoration(
                    requireContext(),
                    1,
                    dpToPx(16f).toInt(),
                    R.color.color_21000000,
                    mutableListOf(viewModel.data.size - 1, viewModel.data.size)
                )
            )
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()
        LiveEventBus.get(SortBeanEvent::class.java).observeSticky(this, {
            if (it?.sort == null) {
                viewModel.tvTitle.set("添加物品")
                viewModel.postSortBean?.propCompanyId =
                    SpHelper.decodeInt(Constants.SpKey.MANAGE_COMPANY_ID)
                viewModel.postSortBean?.propCompanyName =
                    SpHelper.decodeString(Constants.SpKey.MANAGE_COMPANY_NAME)
                viewModel.postSortBean?.propCompanyShortName =
                    SpHelper.decodeString(Constants.SpKey.MANAGE_COMPANY_SHORT_NAME)

                val bean = viewModel.data[0]
                bean.rightTitle = viewModel.postSortBean?.propCompanyShortName
                mAdapter.setData(0, bean)
            } else {
                viewModel.tvTitle.set("编辑物品")
            }
            viewModel.sortBean = it?.sort
        })
        viewModel.uc.selectedImageEvent.observe(this, {
            showChoosePhoto()
        })

        viewModel.uc.loadCategoryEvent.observe(this, {

        })
    }

    private fun itemCommand(position: Int) {
        when (position) {
            1 -> {
                viewModel.getClassStockList(viewModel.postSortBean?.propCompanyId)
            }
            6 -> {
                val list = if (viewModel.sortBean?.classStatus == 2) {
                    mutableListOf("单品")
                } else {
                    mutableListOf("单品", "数量")
                }
                ListSheetDialogFragment.showBottomSheet(
                    parentFragmentManager,
                    list
                ) {
                    val bean = viewModel.data[position]
                    bean.rightTitle = list[it]
                    mAdapter.setData(position, bean)
                }
            }
            7 -> {
                val list = if (viewModel.sortBean?.manageMode == 1) {
                    mutableListOf("耐用品", "消耗品")
                } else {
                    mutableListOf("耐用品")
                }

                ListSheetDialogFragment.showBottomSheet(
                    parentFragmentManager,
                    list
                ) {
                    val bean = viewModel.data[position]
                    bean.rightTitle = list[it]
                    mAdapter.setData(position, bean)
                }
            }
            8 -> {
                val list = if (viewModel.sortBean?.manageMode == 1) {
                    mutableListOf("个别计价法")
                } else {
                    mutableListOf("移动加权平均法", "先进先出法")
                }
                ListSheetDialogFragment.showBottomSheet(
                    parentFragmentManager,
                    list
                ) {
                    val bean = viewModel.data[position]
                    bean.rightTitle = list[it]
                    mAdapter.setData(position, bean)
                }
            }
        }
    }

    private fun showChoosePhoto() {
        val list = mutableListOf("拍照", "相册")
        ListSheetDialogFragment.showBottomSheet(
            parentFragmentManager,
            list
        ) {
            when (it) {
                1 -> {
                    PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideEngine.createGlideEngine())
                        .videoMaxSecond(15)
                        .isShowOutLengthVideos(true)
                        .isMaxSelectEnabledMask(true)
                        .maxSelectNum(1)
                        .maxVideoSelectNum(4)
                        .imageSpanCount(4)
                        .isWithVideoImage(true)
                        .selectionMode(PictureConfig.MULTIPLE)
                        .isCamera(false)
                        .isEditorImage(true)
                        .selectionData(selectList)
                        .isCompress(true)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: MutableList<LocalMedia>?) {
                                selectList.clear()
                                if (result != null) {
                                    selectList.addAll(result)
                                }
                                if (result?.isNotEmpty() == true) {
                                    viewModel.selectedImageUrl.set(result.first().compressPath)
                                }
                            }

                            override fun onCancel() {
                            }
                        })
                }
                2 -> {
                    PictureSelector.create(activity)
                        .openCamera(PictureMimeType.ofImage())
                        .recordVideoSecond(15)
                        .imageEngine(GlideEngine.createGlideEngine())
                        .isUseCustomCamera(true)
                        .isCompress(true)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: MutableList<LocalMedia>?) {
                                if (result?.isNotEmpty() == true) {
                                    viewModel.selectedImageUrl.set(result.first().compressPath)
                                }
                            }

                            override fun onCancel() {
                            }
                        })
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        footerBinding?.unbind()
    }
}